﻿using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Xpedite.Localization;
using Xpedite.Resources;
using Xpedite.Resources.Builders;
using Xpedite.Resources.Combiners;
using Xpedite.Resources.Definitions;

/* Copyright (c) 2010 CBaxter
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
 * IN THE SOFTWARE. 
 */

namespace Xpedite.Test.Resources.Definitions
{
  [TestClass]
  public class DefinitionBaseTest
  {
    private readonly Mock<IResourceBuilderFactory> _builderFactory = new Mock<IResourceBuilderFactory>(MockBehavior.Strict);
    private readonly Mock<IResourceUrlGenerator> _urlGenerator = new Mock<IResourceUrlGenerator>(MockBehavior.Strict);
    private readonly Mock<ICombinerFactory> _combinerFactory = new Mock<ICombinerFactory>(MockBehavior.Strict);
    private readonly Mock<IResourceContainer> _resource = new Mock<IResourceContainer>(MockBehavior.Strict);
    private readonly Mock<IResourceBuilder> _builder = new Mock<IResourceBuilder>(MockBehavior.Strict);
    private readonly Mock<IResourceCache> _cache = new Mock<IResourceCache>(MockBehavior.Strict);
    private readonly Mock<ICombiner> _combiner = new Mock<ICombiner>(MockBehavior.Strict);
    private readonly DefinitionArgs _definitionArgs;
    private readonly DefinitionBase _definition;

    public DefinitionBaseTest()
    {
      _definitionArgs = new DefinitionArgs(_cache.Object, _urlGenerator.Object, _builderFactory.Object, _combinerFactory.Object);
      _definition = new FakeDefinition(_definitionArgs, "ReferenceName", ".*");
    }

    [TestMethod]
    public void TestCtorVerifiesReferenceName()
    {
      Expect.Exception(
          () => new FakeDefinition(_definitionArgs, ".InvalidName", NamingPattern.CssClass),
          new XpediteException(String.Format(ExceptionMessages.InvalidCompositeResourceReferenceName, ".InvalidName", ResourceType.Unknown))
        );
    }

    [TestMethod]
    public void TestReferenceResourceVerifiesReferenceName()
    {
      var definition = new FakeDefinition(_definitionArgs, "ValidDefinitionName", NamingPattern.CssClass);
      var resourceUrl = CreateLocalResourceUrl("http://localhost/resource.url", @"C:\SomeFile.ext");
      var namedResourceUrl = CreateNamedResourceUrl(".InvalidResourceName", resourceUrl);

      Expect.Exception(
          () => definition.ReferenceResource(namedResourceUrl),
          new XpediteException(String.Format(ExceptionMessages.InvalidResourceReferenceName, ".InvalidResourceName", "ValidDefinitionName", ResourceType.Unknown))
        );
    }

    [TestMethod]
    public void TestReferenceResourceUsingLocalResource()
    {
      var resourceUrl = CreateLocalResourceUrl("http://localhost/resource.url", @"C:\SomeFile.ext");
      var capturedFactory = new CapturedValue<Func<IResourceContainer>>();
      var namedResourceUrl = CreateNamedResourceUrl("resource1", resourceUrl);

      _cache.Setup(mock => mock.GetOrCreateWithFileDependency(resourceUrl, It.Is(capturedFactory.Match), @"C:\SomeFile.ext")).Returns(_resource.Object);

      _definition.ReferenceResource(namedResourceUrl);

      Assert.AreEqual(1, _definition.References.Count());
      Assert.AreEqual(1, _definition.Resources.Count());

      //Verify Factory Create
      _builderFactory.Setup(mock => mock.Create(ResourceType.Unknown, namedResourceUrl.Value)).Returns(_builder.Object);
      _builder.Setup(mock => mock.Build()).Returns(_resource.Object);
      capturedFactory.Value.Invoke();
    }

    [TestMethod]
    public void TestReferenceResourceUsingRemoteResource()
    {
      var resourceUrl = CreateRemoteResourceUrl("http://remotehost/resource.url");
      var capturedFactory = new CapturedValue<Func<IResourceContainer>>();
      var namedResourceUrl = CreateNamedResourceUrl("resource1", resourceUrl);

      _cache.Setup(mock => mock.GetOrCreateWithNoDependency(resourceUrl, It.Is(capturedFactory.Match))).Returns(_resource.Object);

      _definition.ReferenceResource(namedResourceUrl);

      Assert.AreEqual(1, _definition.References.Count());
      Assert.AreEqual(1, _definition.Resources.Count());

      //Verify Factory Create
      _builderFactory.Setup(mock => mock.Create(ResourceType.Unknown, namedResourceUrl.Value)).Returns(_builder.Object);
      _builder.Setup(mock => mock.Build()).Returns(_resource.Object);
      capturedFactory.Value.Invoke();
    }

    [TestMethod]
    public void TestReferenceResourceWithDuplicateReferenceName()
    {
      var resourceUrl = CreateRemoteResourceUrl("http://remotehost/resource1.url");
      var namedResourceUrl1 = CreateNamedResourceUrl("resource1", resourceUrl);
      var namedResourceUrl2 = CreateNamedResourceUrl("resource1", resourceUrl);

      _cache.Setup(mock => mock.GetOrCreateWithNoDependency(resourceUrl, It.IsAny<Func<IResourceContainer>>())).Returns(_resource.Object);

      _definition.ReferenceResource(namedResourceUrl1);

      Expect.Exception(() => _definition.ReferenceResource(namedResourceUrl2), new XpediteException(String.Format(ExceptionMessages.DuplicateResourceReferenceName, "resource1", "ReferenceName")));
    }

    [TestMethod]
    public void TestReferenceResources()
    {
      var resourceUrl1 = CreateRemoteResourceUrl("http://remotehost/resource1.url");
      var resourceUrl2 = CreateRemoteResourceUrl("http://remotehost/resource2.url");
      var namedResourceUrl1 = CreateNamedResourceUrl("resource1", resourceUrl1);
      var namedResourceUrl2 = CreateNamedResourceUrl("resource2", resourceUrl2);
      var anotherResource = new Mock<IResourceContainer>(MockBehavior.Strict);

      _cache.Setup(mock => mock.GetOrCreateWithNoDependency(resourceUrl1, It.IsAny<Func<IResourceContainer>>())).Returns(_resource.Object);
      _cache.Setup(mock => mock.GetOrCreateWithNoDependency(resourceUrl2, It.IsAny<Func<IResourceContainer>>())).Returns(anotherResource.Object);

      _definition.ReferenceResources(new [] { namedResourceUrl1, namedResourceUrl2 });

      Assert.AreEqual(2, _definition.References.Count());
      Assert.AreEqual(2, _definition.Resources.Count());
    }

    [TestMethod]
    public void TestGetResourceWhereResourceNotFound()
    {
      Expect.Exception(() => _definition.GetResource("MyResource"), new XpediteException(String.Format(ExceptionMessages.UnknownResourceReferenceName, "MyResource", "ReferenceName")));
    }

    [TestMethod]
    public void TestGetResourceWhereResourceFound()
    {
      TestReferenceResources();

      Assert.AreSame(_resource.Object, _definition.GetResource("resource1"));
    }

    private IResourceUrl CreateLocalResourceUrl(String url)
    {
      var resourceUrl = new Mock<IResourceUrl>(MockBehavior.Strict);

      resourceUrl.SetupGet(mock => mock.PhysicalPath).Returns((String)null);
      resourceUrl.SetupGet(mock => mock.VirtualPath).Returns("url");
      resourceUrl.SetupGet(mock => mock.IsLocal).Returns(true);

      return resourceUrl.Object;
    }

    private IResourceUrl CreateLocalResourceUrl(String url, String physicalPath)
    {
      var resourceUrl = new Mock<IResourceUrl>(MockBehavior.Strict);

      resourceUrl.SetupGet(mock => mock.PhysicalPath).Returns(physicalPath);
      resourceUrl.SetupGet(mock => mock.VirtualPath).Returns("url");
      resourceUrl.SetupGet(mock => mock.IsLocal).Returns(true);

      return resourceUrl.Object;
    }

    private IResourceUrl CreateRemoteResourceUrl(String url)
    {
      var resourceUrl = new Mock<IResourceUrl>(MockBehavior.Strict);

      resourceUrl.SetupGet(mock => mock.PhysicalPath).Returns((String)null);
      resourceUrl.SetupGet(mock => mock.VirtualPath).Returns("url");
      resourceUrl.SetupGet(mock => mock.IsLocal).Returns(false);

      return resourceUrl.Object;
    }

    private INamedValue<IResourceUrl> CreateNamedResourceUrl(String name, IResourceUrl resourceUrl)
    {
      var namedResourceUrl = new Mock<INamedValue<IResourceUrl>>(MockBehavior.Strict);

      namedResourceUrl.SetupGet(mock => mock.Name).Returns(name);
      namedResourceUrl.SetupGet(mock => mock.Value).Returns(resourceUrl);

      return namedResourceUrl.Object;
    }

    private class FakeDefinition : DefinitionBase
    {
      public FakeDefinition(DefinitionArgs args, String referenceName, String namingPattern)
        : base(args, referenceName, new NamingRule(namingPattern))
      { }

      public override ResourceType ResourceType
      {
        get { return ResourceType.Unknown; }
      }

      public override void EmitResource(System.Web.UI.HtmlTextWriter writer)
      {
        throw new NotImplementedException();
      }
    }
  }
}
